package com.teddy.model;

import java.io.InputStream;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.teddy.util.Constants;

public class Deserializer {
	
	public static Model deserializeModel(String uri){
		Model m = ModelFactory.createDefaultModel();
		
		InputStream in =  com.hp.hpl.jena.util.FileManager.get().open(uri);
		if (in == null) {
		    throw new IllegalArgumentException(
		                                 "File: " + uri + " not found");
		}
		m = buildModel(m, in);
		
		return m;
	}
	
	protected static Model readRdf_Abbrev(Model m, InputStream in){
		try{
			m.read(in, Constants.RDF_ABBREV_FORMAT);
			return m;
		}
		catch(Exception ex){
			return null;
		}
	}
	protected static Model readRdf_XML(Model m, InputStream in){
		try{
			m.read(in, Constants.RDF_XML_FORMAT);
			return m;
		}
		catch(Exception ex){
			return readTurtle(m, in);
		}
	}
	protected static Model readTurtle(Model m, InputStream in){
		try{
			m.read(in, Constants.TURTLE_FORMAT);
			return m;
		}
		catch(Exception ex){
			return readRdf_Abbrev(m, in);
		}
	}
	
	protected static Model buildModel(Model m, InputStream in){
		return readRdf_XML(m, in);
	}

}
